<template>
  <j-modal
    switchFullscreen
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk" v-if="!disableSubmit">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-tabs default-active-key="1" @change="callback">
              <a-tab-pane key="1" tab="基础信息"></a-tab-pane>
            </a-tabs>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="DMS订单类型">
              <cn-dict-select-tag v-decorator="['dmsOrderType',validatorRules.terminalName ]" dict-code="dms_order_type" triggerChange
                                  :disabled="disableSubmit" placeholder="请选择"></cn-dict-select-tag>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="客户类型">
              <cn-dict-select-tag v-decorator="['customerType',validatorRules.terminalName ]" dict-code="cust_type" triggerChange
                                  :disabled="disableSubmit" placeholder="请选择"></cn-dict-select-tag>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-tabs default-active-key="1" @change="callback">
              <a-tab-pane key="1" tab="校验信息"></a-tab-pane>
            </a-tabs>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否校验信贷"
            >
              <vxe-switch
                v-model="model['isCheckCredit']"
                :open-value="1"
                :close-value="0"></vxe-switch>

            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否校验库存"
            >
              <vxe-switch
                v-model="model['isCheckInv']"
                :open-value="1"
                :close-value="0"></vxe-switch>

            </a-form-item>
          </a-col>
<!--          <a-col :md="12" :sm="24">-->
<!--            <a-form-item-->
<!--              :labelCol="labelCol"-->
<!--              :wrapperCol="wrapperCol"-->
<!--              label="是否校验车型"-->
<!--            >-->
<!--              <vxe-switch-->
<!--                v-model="model['isCheckModel']"-->
<!--                :open-value="1"-->
<!--                :close-value="0"></vxe-switch>-->

<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否校验最小托盘量"
            >
              <vxe-switch
                v-model="model['isCheckTray']"
                :open-value="1"
                :close-value="0"></vxe-switch>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否校验起订量"
            >
              <vxe-switch
                v-model="model['isCheckBooking']"
                :open-value="1"
                :close-value="0"></vxe-switch>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div style="display: flex;padding-left: 5.5%;border-top: 1px dashed #fefefe;padding-top:10px">
      </div>
      <a-tabs default-active-key="1" @change="callback">
        <a-tab-pane key="1" tab="配置信息">
          <a-button type="primary" @click="insertEvent" style="margin-bottom: 8px" :disabled="disableSubmit">新增
          </a-button>
          <vxe-table
            border
            resizable
            show-overflow
            size="mini"
            ref="xTable"
            height="300"
            :loading="loading"
            :data="tableData"
            :edit-rules="validRules"
            :edit-config="{trigger: 'click', mode: 'row', enabled:!disableSubmit, showUpdateStatus: true, showInsertStatus: true}">
            <vxe-column type="checkbox" width="40"></vxe-column>
            <vxe-column field="dataTypeCode" title="类型名称" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ formatTableValue(fieldTypeList, row.dataTypeCode) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.dataTypeCode" placeholder="类型名称" clearable>
                  <vxe-option v-for="(item,index) in  fieldTypeList" :key="index" :value="item.value" :label="item.label" :disabled="$refs.xTable.getTableData().tableData.some(v=>v.dataTypeCode==item.value)"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="dataTypeValue" title="类型值" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input v-model="row.dataTypeValue" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="bookLine" title="本品行" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input v-model="row.bookLine" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="giftLine" title="赠品行" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input v-model="row.giftLine" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="120">
              <template #default="{ row }">
                <vxe-button status="warning" content="删除" @click="removeRowEvent(row)"
                            :disabled="disableSubmit"></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction, httpAction, postAction } from '@/api/manage'
import { pick } from 'lodash'
import moment from 'moment'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import CnAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import { isMobile, isPermit } from '@/utils/validate'
import UploadImage from '@/components/upload-image/UploadImage'
import JImageUpload from '@/components/cn-form/JImageUpload'
import Area from '@/components/utils/Area'
import JUpload from '@/components/cn-form/JUpload'
import { initDictOptions } from '@comp/dict/CnDictSelectUtil'

const generateUUID = function (withSeparator = true) {
  let d = new Date().getTime()
  d = (d + '').substring(5, (d + '').length)
  return d * 1
}
export default {
  name: 'terminal-modal',
  components: { JTreeSelect, CnAreaLinkage, UploadImage, JImageUpload, JUpload },
  data() {
    return {
      falg: 1,
      validRules: {
        fieldName: [
          { required: true, message: '字段名称必须填写' }
        ],
        fieldValue: [
          { required: true, message: '表字段必须填写' }
        ],
        fieldType: [
          { required: true, message: '表字段类型必须填写' }
        ],
        fieldLen: [
          { required: true, message: '表字段长度必须填写' }
        ],
      },
      showList: [
        { label: '是', value: '1' },
        { label: '否', value: '0' }
      ],
      controlTypeList: [
        { label: '文本', value: '1' },
        { label: '输入框', value: '2' },
        { label: '选择框', value: '3' }
      ],

      dataSurces: [],
      title: '操作',
      visible: false,
      model: {},
      tableData: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      selectedRowKeys: [],
      selectionRows: [],
      validatorRules: {
        terminalName: {
          rules: [
            { required: true, message: ' ' }
          ]
        },
      },
      addOrUpdateUrl: window._CONFIG['domianURL'] + '/orderconfig/cnOrderConfig/saveOrUpdate'
    }
  },
  created() {
    this.initAreaData()
    this.initDictConfig()
  },
  methods: {
    moment,
    add() {
      this.edit({})
    },
    initDictConfig() {
      //初始化字典 - 流程分类
      initDictOptions('order_config_type').then((res) => {
        if (res.success) {
          this.fieldTypeList = res.result.map(item => Object.assign({}, {
            label: item.dictDataDesc,
            value: item.dictDataCode
          }))
        }
      })
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        if (record.id) {
          this.tableData = record.itemVos || []
        }
        this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.tableData = []
    },
    async insertEvent() {
      const $table = this.$refs.xTable
      if($table.getTableData().tableData.length>=this.fieldTypeList.length){
        this.$message.warning(`最大只能添加${this.fieldTypeList.length}条！`)
        return
      }
      const newRecord = {}
      const { row: newRow } = await $table.insert(newRecord)
      await $table.setActiveRow(newRow)
    },
    async removeSelectEvent() {
      const $table = this.$refs.xTable
      await $table.removeCheckboxRow()
    },
    formatTableValue(list = [], value) {
      console.log(list, value)
      if (list.length) {
        let item = list.find(val => val.value == value)
        console.log(item)
        if (item) {
          return item.label
        } else {
          return ''
        }
      } else {
        return ''
      }
    },

    async handleOk() {
      const that = this
      // 触发表单验证
      const $table = this.$refs.xTable
      const { tableData } = $table.getTableData()
      const errMap = await $table.validate().catch(errMap => errMap)
      if (errMap) {
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values, {
            itemVos: tableData,
          })
          httpAction(this.addOrUpdateUrl, formData, 'post').then((res) => {
            if (res.success) {
              this.close()
              that.$emit('ok')
              that.$message.success(res.message)
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    async removeRowEvent(row) {
      const $table = this.$refs.xTable
      await $table.remove(row)
    },
    handleCancel() {
      this.close()
    },
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area()
      }
    },

    // 新增行
    handleAddRow(name) {
      console.log(this[name])
      this[name].push({ id: generateUUID(false) })
    }

  }
}
</script>

<style scoped>
.gonghuoxinxi {
  width: 100%;
  border-bottom: 1px dashed black;
  margin: 10px 0;
  padding: 15px 5px;
  display: flex;
  flex-direction: column;
}
</style>
